<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">


<meta name="google-site-verification" content="E9deYnivN5MuHMuIfiMZZfS0alv-d_0UjcwjBL79lGU" />



<meta name="baidu-site-verification" content="iHYWJxscwD" />










<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />



  <meta name="google-site-verification" content="true" />








  <meta name="baidu-site-verification" content="true" />







  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="学习笔记,量化投资,kaggle竞赛,深度学习,LSTM,pytorch," />










<meta name="description" content="又尝试了一下神经网络，用的两个隐藏层，用optuna调参，结果如下: 用调出来的最佳参数:{‘hide1_dim’: 118, ‘hide2_dim’: 142, ‘optimizer’: ‘Adam’, ‘lr’: 0.0006778517964352916, ‘epochs’: 110}提交看看。 哈哈，终于不再是零分了！这是用10%的数据调参的。找个GPU服务器用完整数据试试吧。用kaggl">
<meta property="og:type" content="article">
<meta property="og:title" content="量化投资学习笔记100——kaggle量化投资比赛记录8-LSTM">
<meta property="og:url" content="https://zwdnet.github.io/2021/01/26/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0100%E2%80%94%E2%80%94kaggle%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84%E6%AF%94%E8%B5%9B%E8%AE%B0%E5%BD%958-LSTM/index.html">
<meta property="og:site_name" content="赵瑜敏的口腔医学专业学习博客">
<meta property="og:description" content="又尝试了一下神经网络，用的两个隐藏层，用optuna调参，结果如下: 用调出来的最佳参数:{‘hide1_dim’: 118, ‘hide2_dim’: 142, ‘optimizer’: ‘Adam’, ‘lr’: 0.0006778517964352916, ‘epochs’: 110}提交看看。 哈哈，终于不再是零分了！这是用10%的数据调参的。找个GPU服务器用完整数据试试吧。用kaggl">
<meta property="og:locale">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/71/01.jpg">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/71/02.jpg">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/71/03.jpg">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/71/04.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/71/05.jpg">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/71/06.jpg">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/71/07.jpg">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/71/08.jpg">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/71/09.jpg">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/71/10.jpg">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/71/11.jpg">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/71/12.jpg">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/71/13.jpg">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/wx.jpg">
<meta property="article:published_time" content="2021-01-26T04:14:59.000Z">
<meta property="article:modified_time" content="2021-01-26T12:51:40.000Z">
<meta property="article:author" content="赵瑜敏">
<meta property="article:tag" content="学习笔记">
<meta property="article:tag" content="量化投资">
<meta property="article:tag" content="kaggle竞赛">
<meta property="article:tag" content="深度学习">
<meta property="article:tag" content="LSTM">
<meta property="article:tag" content="pytorch">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/71/01.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zwdnet.github.io/2021/01/26/量化投资学习笔记100——kaggle量化投资比赛记录8-LSTM/"/>





  <title>量化投资学习笔记100——kaggle量化投资比赛记录8-LSTM | 赵瑜敏的口腔医学专业学习博客</title>
  








<meta name="generator" content="Hexo 5.4.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">赵瑜敏的口腔医学专业学习博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zwdnet.github.io/2021/01/26/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0100%E2%80%94%E2%80%94kaggle%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84%E6%AF%94%E8%B5%9B%E8%AE%B0%E5%BD%958-LSTM/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/tx.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="赵瑜敏的口腔医学专业学习博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">量化投资学习笔记100——kaggle量化投资比赛记录8-LSTM</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2021-01-26T04:14:59+00:00">
                2021-01-26
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84/" itemprop="url" rel="index">
                    <span itemprop="name">量化投资</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                  <span class="post-meta-divider">|</span>
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  1.9k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  7
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>又尝试了一下神经网络，用的两个隐藏层，用optuna调参，结果如下:<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/71/01.jpg"></p>
<p>用调出来的最佳参数:<br>{‘hide1_dim’: 118, ‘hide2_dim’: 142, ‘optimizer’: ‘Adam’, ‘lr’: 0.0006778517964352916, ‘epochs’: 110}<br>提交看看。<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/71/02.jpg"></p>
<p>哈哈，终于不再是零分了！这是用10%的数据调参的。找个GPU服务器用完整数据试试吧。<br>用kaggle上的GPU来跑调参程序(每周可以用36小时)，跑了八个多小时，近600次。<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/71/03.jpg"></p>
<p>最佳的是第553次，最佳参数:{‘hide1_dim’: 192, ‘hide2_dim’: 10, ‘optimizer’: ‘Adam’, ‘lr’: , ‘epochs’: 192}，用这些参数在kaggle里提交，结果，3270.173分。<br>下面想试试传说中时间序列数据分析的神器LSTM。找了一圈资料，看了一头雾水。先实操吧，照<a target="_blank" rel="noopener" href="https://zhuanlan.zhihu.com/p/104475016">这个</a>来:<br>使用正弦函数和余弦函数构造时间序列，构造模型学习正弦函数与余弦函数之间的映射关系，通过输入的正弦函数值来预测余弦函数值。<br>如果不考虑时间因素，一个正弦输入值对应多个余弦值，如sin(pi/6)=sin(7pi/6)，但cos(pi/6)≠cos(7pi/6)。这种情况，传统神经网络不太适用。<br>取正弦值作为LSTM的输入，预测余弦函数的值。1个输入神经元，1个输出神经元，16个隐藏神经元。平均绝对误差(LMSE)作为损失误差，使用Adam优化算法来LSTM神经网络。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="keyword">import</span> torch</span><br><span class="line"><span class="keyword">from</span> torch <span class="keyword">import</span> nn</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> plt</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">LstmRNN</span>(<span class="params">nn.Module</span>):</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self, input_size, hidden_size = <span class="number">1</span>, output_size = <span class="number">1</span>, num_layers = <span class="number">1</span></span>):</span></span><br><span class="line">        <span class="built_in">super</span>().__init__()</span><br><span class="line">        self.lstm = nn.LSTM(input_size, hidden_size, num_layers)</span><br><span class="line">        self.forwardCalculation = nn.Linear(hidden_size, output_size)</span><br><span class="line">        </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">forward</span>(<span class="params">self, _x</span>):</span></span><br><span class="line">        x, _ = self.lstm(_x)</span><br><span class="line">        s, b, h = x.shape <span class="comment"># seq_len, batch, hidden_size</span></span><br><span class="line">        x = x.view(s*b, h)</span><br><span class="line">        x = self.forwardCalculation(x)</span><br><span class="line">        x = x.view(s, b, -<span class="number">1</span>)</span><br><span class="line">        <span class="keyword">return</span> x</span><br><span class="line">        </span><br><span class="line">        </span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">LSTM</span>():</span></span><br><span class="line">    <span class="comment"># 建立数据</span></span><br><span class="line">    data_len = <span class="number">200</span></span><br><span class="line">    t = np.linspace(<span class="number">0</span>, <span class="number">12</span>*np.pi, data_len)</span><br><span class="line">    sin_t = np.sin(t)</span><br><span class="line">    cos_t = np.cos(t)</span><br><span class="line">    </span><br><span class="line">    dataset = np.zeros((data_len, <span class="number">2</span>))</span><br><span class="line">    dataset[:, <span class="number">0</span>] = sin_t</span><br><span class="line">    dataset[:, <span class="number">1</span>] = cos_t</span><br><span class="line">    dataset = dataset.astype(<span class="string">&quot;float32&quot;</span>)</span><br><span class="line">    </span><br><span class="line">    <span class="comment"># 划分数据</span></span><br><span class="line">    train_data_ratio = <span class="number">0.5</span></span><br><span class="line">    train_data_len = <span class="built_in">int</span>(data_len*train_data_ratio)</span><br><span class="line">    train_x = dataset[:train_data_len, <span class="number">0</span>]</span><br><span class="line">    train_y = dataset[:train_data_len, <span class="number">1</span>]</span><br><span class="line">    INPUT_FEATURES_NUM = <span class="number">1</span></span><br><span class="line">    OUTPUT_FEATURES_NUM = <span class="number">1</span></span><br><span class="line">    t_for_training = t[:train_data_len]</span><br><span class="line">    </span><br><span class="line">    test_x = dataset[train_data_len:, <span class="number">0</span>]</span><br><span class="line">    test_y = dataset[train_data_len:, <span class="number">1</span>]</span><br><span class="line">    t_for_testing = t[train_data_len:]</span><br><span class="line">    </span><br><span class="line">    <span class="comment"># 训练</span></span><br><span class="line">    train_x_tensor = train_x.reshape(-<span class="number">1</span>, <span class="number">5</span>, INPUT_FEATURES_NUM) <span class="comment"># 分5批</span></span><br><span class="line">    train_y_tensor = train_y.reshape(-<span class="number">1</span>, <span class="number">5</span>, OUTPUT_FEATURES_NUM) <span class="comment"># 分5批</span></span><br><span class="line">    train_x_tensor = torch.from_numpy(train_x_tensor)</span><br><span class="line">    train_y_tensor = torch.from_numpy(train_y_tensor)</span><br><span class="line">    </span><br><span class="line">    lstm_model = LstmRNN(INPUT_FEATURES_NUM, <span class="number">16</span>, output_size = OUTPUT_FEATURES_NUM, num_layers = <span class="number">1</span>)</span><br><span class="line">    print(<span class="string">&#x27;LSTM model:&#x27;</span>, lstm_model)</span><br><span class="line">    print(<span class="string">&#x27;model.parameters:&#x27;</span>, lstm_model.parameters)</span><br><span class="line">    </span><br><span class="line">    loss_fn = nn.MSELoss()</span><br><span class="line">    lr = <span class="number">1e-2</span></span><br><span class="line">    optimizer = torch.optim.Adam(lstm_model.parameters(), lr)</span><br><span class="line">    </span><br><span class="line">    max_epochs = <span class="number">10000</span></span><br><span class="line">    <span class="keyword">for</span> epoch <span class="keyword">in</span> <span class="built_in">range</span>(max_epochs):</span><br><span class="line">        output = lstm_model(train_x_tensor)</span><br><span class="line">        loss = loss_fn(output, train_y_tensor)</span><br><span class="line">        loss.backward()</span><br><span class="line">        optimizer.step()</span><br><span class="line">        optimizer.zero_grad()</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">if</span> loss.item() &lt; <span class="number">1e-4</span>:</span><br><span class="line">            print(<span class="string">&#x27;Epoch [&#123;&#125;/&#123;&#125;], Loss: &#123;:.5f&#125;&#x27;</span>.<span class="built_in">format</span>(epoch+<span class="number">1</span>, max_epochs, loss.item()))</span><br><span class="line">            print(<span class="string">&quot;The loss value is reached&quot;</span>)</span><br><span class="line">            <span class="keyword">break</span></span><br><span class="line">        <span class="keyword">elif</span> (epoch+<span class="number">1</span>) % <span class="number">100</span> == <span class="number">0</span>:</span><br><span class="line">            print(<span class="string">&#x27;Epoch [&#123;&#125;/&#123;&#125;], Loss: &#123;:.5f&#125;&#x27;</span>.<span class="built_in">format</span>(epoch+<span class="number">1</span>, max_epochs, loss.item()))</span><br><span class="line">            </span><br><span class="line">    <span class="comment"># 用模型预测</span></span><br><span class="line">    <span class="comment"># 训练集上</span></span><br><span class="line">    predictive_y_for_training = lstm_model(train_x_tensor)</span><br><span class="line">    predictive_y_for_training = predictive_y_for_training.view(-<span class="number">1</span>, OUTPUT_FEATURES_NUM).data.numpy()</span><br><span class="line">    </span><br><span class="line">    <span class="comment"># 切换为测试状态</span></span><br><span class="line">    lstm_model = lstm_model.<span class="built_in">eval</span>()</span><br><span class="line">    <span class="comment"># 用测试集预测</span></span><br><span class="line">    test_x_tensor = test_x.reshape(-<span class="number">1</span>, <span class="number">5</span>, INPUT_FEATURES_NUM) </span><br><span class="line">    test_x_tensor = torch.from_numpy(test_x_tensor)</span><br><span class="line">    predictive_y_for_testing = lstm_model(test_x_tensor)</span><br><span class="line">    predictive_y_for_testing = predictive_y_for_testing.view(-<span class="number">1</span>, OUTPUT_FEATURES_NUM).data.numpy()</span><br><span class="line">    </span><br><span class="line">    <span class="comment"># 画图</span></span><br><span class="line">    plt.figure()</span><br><span class="line">    plt.plot(t_for_training, train_x, <span class="string">&#x27;g&#x27;</span>, label=<span class="string">&#x27;sin_trn&#x27;</span>)</span><br><span class="line">    plt.plot(t_for_training, train_y, <span class="string">&#x27;b&#x27;</span>, label=<span class="string">&#x27;ref_cos_trn&#x27;</span>)</span><br><span class="line">    plt.plot(t_for_training, predictive_y_for_training, <span class="string">&#x27;y--&#x27;</span>, label=<span class="string">&#x27;pre_cos_trn&#x27;</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    plt.plot(t_for_testing, test_x, <span class="string">&#x27;c&#x27;</span>, label=<span class="string">&#x27;sin_tst&#x27;</span>)</span><br><span class="line">    plt.plot(t_for_testing, test_y, <span class="string">&#x27;k&#x27;</span>, label=<span class="string">&#x27;ref_cos_tst&#x27;</span>)</span><br><span class="line">    plt.plot(t_for_testing, predictive_y_for_testing, <span class="string">&#x27;m--&#x27;</span>, label=<span class="string">&#x27;pre_cos_tst&#x27;</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    plt.plot([t[train_data_len], t[train_data_len]], [-<span class="number">1.2</span>, <span class="number">4.0</span>], <span class="string">&#x27;r--&#x27;</span>, label=<span class="string">&#x27;separation line&#x27;</span>) <span class="comment"># separation line</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    plt.xlabel(<span class="string">&#x27;t&#x27;</span>)</span><br><span class="line">    plt.ylabel(<span class="string">&#x27;sin(t) and cos(t)&#x27;</span>)</span><br><span class="line">    plt.xlim(t[<span class="number">0</span>], t[-<span class="number">1</span>])</span><br><span class="line">    plt.ylim(-<span class="number">1.2</span>, <span class="number">4</span>)</span><br><span class="line">    plt.legend(loc=<span class="string">&#x27;upper right&#x27;</span>)</span><br><span class="line">    plt.text(<span class="number">14</span>, <span class="number">2</span>, <span class="string">&quot;train&quot;</span>, size = <span class="number">15</span>, alpha = <span class="number">1.0</span>)</span><br><span class="line">    plt.text(<span class="number">20</span>, <span class="number">2</span>, <span class="string">&quot;test&quot;</span>, size = <span class="number">15</span>, alpha = <span class="number">1.0</span>)</span><br><span class="line">    </span><br><span class="line">    plt.savefig(<span class="string">&quot;./output/LSTM.png&quot;</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&quot;__main__&quot;</span>:</span><br><span class="line">    LSTM()</span><br></pre></td></tr></table></figure>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/71/04.png"><br>结果不错。可以看到整个过程跟传统深度网络差不多的，只是激活函数用了nn.LSTM。<br>再看看原理，<a target="_blank" rel="noopener" href="https://blog.csdn.net/Jerr__y/article/details/58598296">《理解LSTM网络》</a><br>原文是英文，打不开了。这是翻译的。<br>传统神经网络没有记忆性，学了后面忘了前面。在循环神经网络(RNNs)中，有一个循环操作，使其能够保留之前学到的内容。<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/71/05.jpg"></p>
<p>某一时刻的输入Xt，通过神经节A得到输出ht，同时当前时刻的状态会作为下一个时刻的输入的一部分。可以把RNN看作是普通神经网络多次复制后的叠加。</p>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/71/06.jpg"><br>对于只需要短期依赖的问题，RNN表现很好。随着关联信息和预测信息间隔很大的长期依赖的问题，RNN很难把它们关联起来。<br>长短期记忆网络(Long Short Term Memory networks，LSTMs)是一种特殊类型的RNN。其本质是能够记住很长时期的信息。所有RNN都是由完全相同的模块复制而成。在普通RNN中该模块中的结构很简单，比如是由一个单一的tanh层组成。在LSTM中，该模块较复杂，用了四个相互作用的层。<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/71/07.jpg"></p>
<p>每条线都传递着一个向量，从一个节点到另一个节点。<br>LSTM的核心思想是模块的状态向量从整个模块穿过，只做少了线性操作。可以实现长时间的记忆保留了。<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/71/08.jpg"></p>
<p>通过门(gates)结构实现选择性让信息通过。主要是通过一个sigmoid的神经层和一个逐点相乘的操作来实现的。每个LSTM有三个这样的门结构:遗忘门(forget gate layer)、传入门(input gate layer)、输出门(output gate layer)。<br>遗忘门:让哪些信息继续通过该模块。输入是h(t-1)和x(t)。输出是值在(0,1)之间的向量，其长度和模块状态C(t-1)一样的。表示让C(t-1)中信息通过的比例，0表示完全不让通过， 1表示让所有信息通过。<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/71/09.jpg"></p>
<p>传入门:决定让多少新信息加入到模块状态中。包括两个步骤。一个sigmoid层决定哪些信息需要更新，一个tanh层生成一个向量，即备选用来更新的内容，C’t。<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/71/10.jpg"></p>
<p>通过C(t-1)与遗忘门的结果相乘，把不想保留的信息忘掉。结果与传入门结果相加，这就是要更新的内容。<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/71/11.jpg"></p>
<p>输出门:决定输出的内容。通过一个sigmoid层决定C(t)中哪些部分被输出，然后将C(t)经过tanh，最后两个结果相乘形成输出结果。<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/71/12.jpg"></p>
<p>输出结果复制两份，一份传给下一个模块，一份作为该模块的输出结果。<br>还有一些变形，就先pass了。<br>最后，尝试用LSTM来解决我们的问题吧。<br><a target="_blank" rel="noopener" href="https://github.com/zwdnet/JSMPwork/blob/main/LSTM_work.py">代码</a><br>在本地跑得很好，用0.01%的数据就达到59%的准确率，但发现一个问题:太费内存了。当我改成用2%的数据跑就报内存不够了。再到kaggle上提交，用所有数据，结果告诉我需要25000G的内存……搜了一下，要缩小batch_size的大小，但我已经是1了呀。只得缩小数据规模。用2%的数据。提交……<br>0分!<br>改了半天，又加了一层sigmoid，再提交<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/71/13.jpg"></p>
<p>唉，先这样吧。接下来打算从头看书。<br>比赛还有二十天就截止了，看学习的进度吧，可能继续折腾，也可能就这样了。到最后再看看拿奖的大神的解法吧。</p>
<p>我发文章的三个地方，欢迎大家在朋友圈等地方分享，欢迎点“在看”。<br>我的个人博客地址：<a href="https://zwdnet.github.io/">https://zwdnet.github.io</a><br>我的知乎文章地址： <a target="_blank" rel="noopener" href="https://www.zhihu.com/people/zhao-you-min/posts">https://www.zhihu.com/people/zhao-you-min/posts</a><br>我的微信个人订阅号：赵瑜敏的口腔医学学习园地</p>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/wx.jpg"></p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>欢迎打赏！感谢支持！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/mm_facetoface_collect_qrcode_1542944836634.png" alt=" 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/1542944857770.jpg" alt=" 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/" rel="tag"># 学习笔记</a>
          
            <a href="/tags/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84/" rel="tag"># 量化投资</a>
          
            <a href="/tags/kaggle%E7%AB%9E%E8%B5%9B/" rel="tag"># kaggle竞赛</a>
          
            <a href="/tags/%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0/" rel="tag"># 深度学习</a>
          
            <a href="/tags/LSTM/" rel="tag"># LSTM</a>
          
            <a href="/tags/pytorch/" rel="tag"># pytorch</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2021/01/23/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B099%E2%80%94%E2%80%94%E5%88%9B%E9%80%A0%E4%BD%A0%E7%9A%84%E7%AC%AC%E4%B8%80%E4%B8%AA%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0%E6%A1%86%E6%9E%B6/" rel="next" title="量化投资学习笔记99——创造你的第一个深度学习框架">
                <i class="fa fa-chevron-left"></i> 量化投资学习笔记99——创造你的第一个深度学习框架
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2021/01/28/%E8%B7%9F%E6%B1%A4%E8%80%81%E5%B8%88%E5%AD%A6%E5%92%AC%E5%90%88%E2%80%94%E2%80%94%E5%92%AC%E5%90%88%E9%A3%8E%E9%99%A9%E7%9A%84%E8%B0%83%E6%8E%A7/" rel="prev" title="跟汤老师学咬合——咬合风险的调控">
                跟汤老师学咬合——咬合风险的调控 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC80MTA2Mi8xNzU4Nw=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/tx.jpg"
                alt="" />
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/%20%7C%7C%20archive">
              
                  <span class="site-state-item-count">452</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">29</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">544</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">本站版权归赵瑜敏所有，如欲转载请与本人联系。</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">1225.8k</span>
  
</div>









<div>
  <script type="text/javascript">var cnzz_protocol = (("https:" == document.location.protocol) ? " https://" : " http://");document.write(unescape("%3Cspan id='cnzz_stat_icon_1275447216'%3E%3C/span%3E%3Cscript src='" + cnzz_protocol + "s11.cnzz.com/z_stat.php%3Fid%3D1275447216%26online%3D1%26show%3Dline' type='text/javascript'%3E%3C/script%3E"));</script>
</div>

        







  <div style="display: none;">
    <script src="//s95.cnzz.com/z_stat.php?id=1275447216&web_id=1275447216" language="JavaScript"></script>
  </div>



        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  





  

  

  

  
  

  

  

  

  
</body>
</html>
